package com.youlu.campus.web.data.service.impl;
import com.youlu.campus.base.common.Constants;

import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.data.entity.DayMemberGroupStatistics;
import com.youlu.campus.web.data.service.DayMemberGroupStatisticsService;
import com.youlu.campus.web.common.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class DayMemberGroupStatisticsServiceImpl extends BaseService implements DayMemberGroupStatisticsService {
    private final Long keyExpire = 24 * 60 * 60L;

    @Override
    public void accumulationActiveMember(String tenantId, String groupId, String userId) {
        log.info(":>>> 开始累加小组组员:{},用户:{}", tenantId, userId);
        String key = this.getDayActiveMemberRedisKey(tenantId);
        try {
            // TODO:RedisTemplate 序列化方式可能存在问题
            Long count = redisTemplate.opsForValue().increment(key, 1L);
            if (count.compareTo(0L) == 1) {
                redisTemplate.expire(key, keyExpire, TimeUnit.SECONDS);
                log.debug(":>>> 设置key:{} 过期时间24小时之后 ", key);
            }
            this.updateAccumulationActiveGroupMember(tenantId, groupId, userId);
        } catch (Exception e) {
            log.error(":>>> 设置租户:{} 的DAU错误:{}", e);

        }
    }

    @Override
    public void accumulationNewMember(String tenantId, String groupId, String userId) {
        log.info(":>>> 开始累加新增小组组员:{},用户:{}", tenantId, userId);
        String key = this.getDayNewMemberRedisKey(tenantId);
        try {
            // TODO:RedisTemplate 序列化方式可能存在问题
            Long count = redisTemplate.opsForValue().increment(key, 1L);
            if (count.compareTo(0L) == 1) {
                redisTemplate.expire(key, keyExpire, TimeUnit.SECONDS);
                log.debug(":>>> 设置key:{} 过期时间24小时之后 ", key);
            }
            this.updateAccumulationNewGroupMember(tenantId, groupId, userId);
        } catch (Exception e) {
            log.error(":>>> 设置租户:{} 的新增小组组员错误:{}", e);

        }
    }

    protected String getDayActiveMemberRedisKey(String tenantId) {
        String key = String.format(Constants.SYSTEM_ACTIVE_GROUP_MEMBER_RPEFIX, tenantId, DateTimeUtils.getDay0Str());
        log.info(":>>> 租户:{} 活跃小组成员的Redis Key:{}", tenantId, key);
        return key;
    }

    protected String getDayNewMemberRedisKey(String tenantId) {
        String key = String.format(Constants.SYSTEM_NEW_GROUP_MEMBER_RPEFIX, tenantId, DateTimeUtils.getDay0Str());
        log.info(":>>> 租户:{} 新增小组成员 Redis Key:{}", tenantId, key);
        return key;
    }

    private void updateAccumulationActiveGroupMember(String tenantId, String groupId, String userId) {
        Query query = new Query();
        Date startTime = DateTimeUtils.getDay0Date();
        Criteria criteria = new Criteria().andOperator(Criteria.where("statisticsTime").gte(DateTimeUtils.dateToISODate(startTime)), Criteria.where("statisticsTime").lte(DateTimeUtils.dateToISODate(new Date(startTime.getTime() + 24 * 60 * 60 * 1000L))));
        query.addCriteria(criteria);
        DayMemberGroupStatistics d = mongoTemplate.findOne(query, DayMemberGroupStatistics.class);
        if (Objects.isNull(d)) {
            d = new DayMemberGroupStatistics();
            d.setActiveMembers(1);
            d.setCreatedTime(new Date());
            d.setDeleted(Boolean.FALSE);
            d.setTenantId(tenantId);
            d.setStatisticsTime(startTime);
            mongoTemplate.insert(d);
            log.info(":>>> 租户:{} 活跃小组成员:{} 统计不存在,新增", tenantId, startTime);
            return;
        }
        Update update = new Update();
        update.inc("activeMembers", 1);
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("id").is(d.getId()));
        mongoTemplate.updateFirst(query1, update, DayMemberGroupStatistics.class);


    }

    private void updateAccumulationNewGroupMember(String tenantId, String groupId, String userId) {
        Query query = new Query();
        Date startTime = DateTimeUtils.getDay0Date();
        Criteria criteria = new Criteria().andOperator(Criteria.where("statisticsTime").gte(DateTimeUtils.dateToISODate(startTime)), Criteria.where("statisticsTime").lte(DateTimeUtils.dateToISODate(new Date(startTime.getTime() + 24 * 60 * 60 * 1000L))));
        query.addCriteria(criteria);
        DayMemberGroupStatistics d = mongoTemplate.findOne(query, DayMemberGroupStatistics.class);
        if (Objects.isNull(d)) {
            d = new DayMemberGroupStatistics();
            d.setNewMembers(1);
            d.setCreatedTime(new Date());
            d.setDeleted(Boolean.FALSE);
            d.setTenantId(tenantId);
            d.setStatisticsTime(startTime);
            mongoTemplate.insert(d);
            log.info(":>>> 租户:{} 新增小组成员:{} 统计不存在,新增", tenantId, startTime);
            return;
        }
        Update update = new Update();
        update.inc("newMembers", 1);
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("id").is(d.getId()));
        mongoTemplate.updateFirst(query1, update, DayMemberGroupStatistics.class);


    }
}
